package beanAction;

import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.tomcat.util.buf.TimeStamp;

import modele.beanEntity.User;
import modele.mapper.UserMapper;

@ManagedBean(name="loginbean")
@SessionScoped
public class LoginBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7701067237232984508L;
	/**
	 * 
	 */

	private String login;
	private String password;
	private boolean logged;
	private boolean adminLogged;
	private User user;
	private Timestamp connectionTime;
	
	public LoginBean(){
		logged=false;
		adminLogged=false;
	}
	
	public void connectAdmin(){
		this.connect();
		if(!adminLogged){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Vous n'êtes pas administrateur", null));
		}
	}
	
	public void connect(){
		if(login != null && password != null){
			 
			try {
				UserMapper um = new UserMapper();
				if((user=um.loginUser(login, password)) != null){
					logged=true;
					connectionTime=new Timestamp(System.currentTimeMillis());
					
					
					if(user.isAdmin()){
						adminLogged=true;
					}
					
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Succès d'authentification", null));
				}else{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login/ Mot de passe incorrect", null));
				}
			} catch (Exception e) {
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Echec lors de l'authentification", null));
			}
			
		}
	}
	
	@PreDestroy
	public void disconnect() throws Exception{
		String page;
		if(logged){
			UserMapper um= new UserMapper();
			long d = (System.currentTimeMillis() - connectionTime.getTime());
			user.setLastConnectionDuration((int)Math.abs(d/60000));
			user.setLastConnection(connectionTime);
			um.updateUser(user);
		}
		if(adminLogged){
			page="admin.jsf";
		}else{
			page="index.jsf";
		}
		logged=false;
		adminLogged=false;
		user=null;
		login=null;
		password=null;
		FacesContext.getCurrentInstance().getExternalContext().redirect(page);
	}
	
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isLogged() {
		return logged;
	}
	
	public User getUser(){
		return user;
	}

	public boolean isAdminLogged() {
		return adminLogged;
	}

	
	
	
}
